package com.ganee.agora.view

import android.app.Activity
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.ganee.agora.R
import com.ganee.agora.adapter.PostEventChooseAdapter
import com.ganee.agora.event.RepeatEvent
import com.ganee.agora.model.*
import com.ganee.agora.utils.GlideEngine
import com.ganee.agora.utils.Md5Util
import com.ganee.agora.viewmodel.PostEventViewModel
import com.ganee.agora.widget.dialog.BottomDialog
import com.ganee.agora.widget.picker.androidpicker.common.util.ConvertUtils
import com.ganee.agora.widget.picker.androidpicker.wheelPicker.picker.DateTimePicker
import com.ganee.baselib.arouter.Constance
import com.ganee.baselib.httprequest.callback.RequestCallback
import com.ganee.baselib.httprequest.callback.RequestMultiplyCallback
import com.ganee.baselib.httprequest.exception.ApiException
import com.ganee.baselib.httprequest.utils.ToastUtil
import com.ganee.baselib.mvvmlibrary.base.BaseActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.hw.videoprocessor.VideoProcessor
import com.hw.videoprocessor.util.VideoProgressListener
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.Permission
import kotlinx.android.synthetic.main.activity_post_event.*
import kotlinx.android.synthetic.main.toolbar_post_event.*
import okhttp3.MediaType
import okhttp3.RequestBody
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File
import java.lang.ref.WeakReference
import java.util.*


//发布活动页面
@Route(path = Constance.ACTIVITY_URL_POST_EVENT)
class PostEventActivity : BaseActivity<PostEventViewModel>(), View.OnClickListener {

    private var startTime: String? = null
    private var endTime: String? = null
    private var activeType: String = "00"
    private var amount: String = "0"
    private val chooseList: MutableList<RepeatListEntity> = mutableListOf()
    private val mChooseList: MutableList<FileEntity> = mutableListOf()
    private var albumAdapter: PostEventChooseAdapter? = null
    private var dialog: BottomDialog? = null
    private var videoNum: Int = 0
    private var picNum: Int = 0

    private val emptyView: View
        get() {
            val view = LayoutInflater.from(this).inflate(R.layout.post_event_empty, post_event_recyclerview.parent as ViewGroup, false)
            val llEmpty = view.findViewById<LinearLayout>(R.id.post_ll_empty) as LinearLayout
            llEmpty.setOnClickListener {
                initChooseAlbumDialog()
            }
            return view
        }

    override fun getViewModel(): PostEventViewModel {
        return ViewModelProviders.of(this@PostEventActivity).get(PostEventViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_post_event)
        ARouter.getInstance().inject(this)
        EventBus.getDefault().register(this)
        AndPermission.with(this@PostEventActivity)
                .runtime()
                .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                .onGranted({ permissions ->

                })
                .onDenied({ permissions ->
                })
                .start()
        initView()
    }

    private fun initView() {
        toolbarTitle.text = "Your Event"
        toolbarCancel.setOnClickListener(this)
        toolbarRight.setOnClickListener(this)
        post_tv_start_time.setOnClickListener(this)
        post_tv_end_time.setOnClickListener(this)
        post_tv_repeat.setOnClickListener(this)
        post_tv_live_platform.setOnClickListener(this)
        post_tv_category.setOnClickListener(this)
        post_event_recyclerview.setHasFixedSize(false)
        post_event_recyclerview.layoutManager = GridLayoutManager(this@PostEventActivity, 3)

        albumAdapter = PostEventChooseAdapter(mChooseList)
        albumAdapter!!.emptyView = emptyView
        albumAdapter!!.onItemClickListener = BaseQuickAdapter.OnItemClickListener { adapter, view, position ->
            val media = adapter.getItem(position) as FileEntity
            when {
                media.fileType == "01" -> {

                }
                media.fileType == "02" -> {

                }
                media.fileType == "03" -> {
                    initChooseAlbumDialog()
                }
            }
        }
        albumAdapter!!.onItemChildClickListener = BaseQuickAdapter.OnItemChildClickListener { adapter, view, position ->
            val entity = adapter.getItem(position) as FileEntity
            when (view.id) {
                R.id.choose_iv_delete -> {
                    for (i in mChooseList.size - 1 downTo 0) {
                        if (entity.filePath == mChooseList[i].filePath) {
                            mChooseList.remove(mChooseList[i])
                        }
                    }
                    albumAdapter!!.notifyDataSetChanged()
                }
            }
        }
        post_event_recyclerview.adapter = albumAdapter
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.toolbarCancel -> {
                finish()
            }
            R.id.toolbarRight -> {
                submit()
            }
            R.id.post_tv_start_time -> {
                initDateStartTimePicker()
            }
            R.id.post_tv_end_time -> {
                initDateEndTimePicker()
            }
            R.id.post_tv_repeat -> {
                ARouter
                        .getInstance()
                        .build(Constance.ACTIVITY_URL_REPEAT)
                        .withString("repeatTitle", post_tv_repeat.text.toString())
                        .navigation()
            }
            R.id.post_tv_live_platform -> {
                ARouter
                        .getInstance()
                        .build(Constance.ACTIVITY_URL_CHOOSE_PLATFORM)
                        .withString("livePlatform", post_tv_live_platform.text.toString())
                        .navigation()
            }
            R.id.post_tv_category -> {
                ARouter
                        .getInstance()
                        .build(Constance.ACTIVITY_URL_CATEGORY)
                        .withString("chooseList", Gson().toJson(chooseList))
                        .navigation()
            }
            R.id.dialog_tv_video -> {
                var flag:Boolean = false
                for(entity in mChooseList){
                    if (entity.fileType == "02"){
                        flag = true
                    }
                }
                if (!flag) {
                    takeVideo()
                } else {
                    ToastUtil.showToast("One video at most")
                }
                dialog!!.dismiss()
            }
            R.id.dialog_tv_photo -> {

                var num:Int = 0
                for(entity in mChooseList){
                    if (entity.fileType == "02" || entity.fileType == "01"){
                        num += 1
                    }
                }
                if (num < 6) {
                    takePhoto()
                } else {
                    ToastUtil.showToast("Six Pictures or Video at most")
                }
                dialog!!.dismiss()
            }
            R.id.dialog_tv_gallery -> {
                chooseAlbum()
                dialog!!.dismiss()
            }
            R.id.dialog_tv_cancel -> {
                dialog!!.dismiss()
            }
        }
    }

    private fun submit() {
        val title = post_et_title.text.toString()
        val host = post_et_user.text.toString()
        val location = post_et_location.text.toString()
        val roundType = post_tv_repeat.text.toString()
        val about = post_et_des.text.toString()
        val activeKind = post_tv_category.text.toString()
        var activeFiles:String? = null
        val list = mutableListOf<String>()
        for(entity in mChooseList){
            if (!TextUtils.isEmpty(entity.fileId)){
                list.add(entity.fileId!!)
            }
        }
        if (list.size > 0) {
            activeFiles = list.joinToString(",")
        }
        val tickets = post_et_tickets.text.toString()
        val liveSoft = post_tv_live_platform.text.toString().trim()
        val livePath = post_et_live_url.text.toString().trim()
        val email = ""
        val timeZone = TimeZone.getDefault().id
        if (!TextUtils.isEmpty(title) &&!TextUtils.isEmpty(host) &&!TextUtils.isEmpty(startTime)
                &&!TextUtils.isEmpty(endTime) &&!TextUtils.isEmpty(activeKind) && !TextUtils.isEmpty(activeFiles)
                && !TextUtils.isEmpty(tickets) && !TextUtils.isEmpty(about)){
            val insertBody = InsertActivityRequestBody("","",title, host, startTime, endTime, location, roundType, about, activeType, amount,activeKind,activeFiles,tickets,"","",livePath,liveSoft,email,timeZone)
            val body = Gson().toJson(insertBody)
            val requestBody = RequestBody.create(MediaType.parse("application/json"), body)
            viewModel.postEvent(requestBody)
        } else {
            ToastUtil.showToast("Please enter information")
        }

    }

    //日期时间选择框
    private fun initDateStartTimePicker() {

        val picker = DateTimePicker(this, DateTimePicker.HOUR_24)
        picker.setCanceledOnTouchOutside(true)
        picker.setUseWeight(true)
        picker.setTopPadding(ConvertUtils.toPx(this, 10f))
        picker.setDateRangeStart(1950, 1, 1)
        picker.setDateRangeEnd(2100, 1, 1)
        val c = Calendar.getInstance()

        picker.setResetWhileWheel(false)
        picker.setSelectedItem(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH), 0, 0)
        picker.setOnDateTimePickListener(object : DateTimePicker.OnYearMonthDayTimePickListener {
            override fun onDateTimePicked(year: String?, month: String, day: String, hour: String, minute: String) {
                post_tv_start_time.text = year + "-" + month + "-" + day + " " + hour + ":" + minute
                post_tv_start_time.setTextColor(ContextCompat.getColor(this@PostEventActivity, R.color.color_little_title))
                startTime = year + month + day + hour + minute
            }
        })
        picker.show()

    }

    private fun initDateEndTimePicker() {

        val picker = DateTimePicker(this, DateTimePicker.HOUR_24)
        picker.setCanceledOnTouchOutside(true)
        picker.setUseWeight(true)
        picker.setTopPadding(ConvertUtils.toPx(this, 10f))
        picker.setDateRangeStart(1950, 1, 1)
        picker.setDateRangeEnd(2100, 1, 1)
        val c = Calendar.getInstance()

        picker.setResetWhileWheel(false)
        picker.setSelectedItem(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH), 0, 0)
        picker.setOnDateTimePickListener(object : DateTimePicker.OnYearMonthDayTimePickListener {
            override fun onDateTimePicked(year: String?, month: String, day: String, hour: String, minute: String) {
                post_tv_end_time.text = year + "-" + month + "-" + day + " " + hour + ":" + minute
                post_tv_end_time.setTextColor(ContextCompat.getColor(this@PostEventActivity, R.color.color_little_title))
                endTime = year + month + day + hour + minute
            }
        })
        picker.show()

    }

    @Subscribe
    public fun getTitle(event: RepeatEvent) {
        if ("Repeat" == event.type) {
            post_tv_repeat.text = event.title
            post_tv_repeat.setTextColor(ContextCompat.getColor(this@PostEventActivity, R.color.color_little_title))
        } else if ("ChoosePlatform" == event.type) {
            post_tv_live_platform.text = event.title
            post_tv_live_platform.setTextColor(ContextCompat.getColor(this@PostEventActivity, R.color.color_little_title))
        } else if ("Category" == event.type) {
            chooseList.clear()
            if (event.title != null) {
                chooseList.addAll(Gson().fromJson(event.title, object : TypeToken<List<RepeatListEntity>>() {}.type))
            }
            val nameList = mutableListOf<String>()
            for (entity in chooseList) {
                nameList.add(entity.title)
            }
            post_tv_category.text = TextUtils.join(",", nameList)
            post_tv_category.setTextColor(ContextCompat.getColor(this@PostEventActivity, R.color.color_little_title))
        }
    }


    //选择图片对话框
    private fun initChooseAlbumDialog() {
        val view = View.inflate(this@PostEventActivity, R.layout.dialog_post_event_choose_picture, null)
        val tvVideo = view.findViewById<TextView>(R.id.dialog_tv_video) as TextView
        val tvPhoto = view.findViewById<TextView>(R.id.dialog_tv_photo) as TextView
        val tvGallery = view.findViewById<TextView>(R.id.dialog_tv_gallery) as TextView
        val tvCancel = view.findViewById<TextView>(R.id.dialog_tv_cancel) as TextView
        tvVideo.setOnClickListener(this)
        tvPhoto.setOnClickListener(this)
        tvGallery.setOnClickListener(this)
        tvCancel.setOnClickListener(this)

        val weakReference = WeakReference<Activity>(this@PostEventActivity)
        if (weakReference.get() != null) {
            dialog = BottomDialog(weakReference.get(), view, false, true)
            dialog!!.show()
        }
    }
    //单独拍照
    private fun takePhoto() {
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage()) // 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                .loadImageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                .setLanguage(LanguageConfig.ENGLISH)
                .maxSelectNum(6) // 最大图片选择数量
                .minSelectNum(0) // 最小选择数量
                .maxVideoSelectNum(1)
                .minVideoSelectNum(0)
                .isWithVideoImage(true)
                .imageSpanCount(4)
                .recordVideoSecond(15)
                .selectionMode(PictureConfig.MULTIPLE) // 多选 or 单选
                .previewImage(true) // 是否可预览图片
                .previewVideo(true) // 是否可预览视频
                .isCamera(true) // 是否显示拍照按钮
                .queryMaxFileSize(15f)
                .cutOutQuality(90) // 裁剪输出质量 默认100
                .minimumCompressSize(100) // 小于100kb的图片不压缩
                .videoQuality(1)// 视频录制质量 0 or 1
                .videoMaxSecond(15)////显示多少秒以内的视频or音频也可适用
                .forResult(object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(result: List<LocalMedia>) {
                        val picList:MutableList<String> = mutableListOf()
                        for (entity in result) {
                            if (entity.mimeType.startsWith("image")){
                                picList.add(entity.realPath)
                            }
                        }
                        showLoading()
                        uploadImage(picList)
                    }

                    override fun onCancel() {

                    }
                })
    }

    //单独拍视频
    private fun takeVideo() {
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofVideo()) // 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                .loadImageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                .setLanguage(LanguageConfig.ENGLISH)
                .maxVideoSelectNum(1)
                .minVideoSelectNum(0)
                .isWithVideoImage(true)
                .imageSpanCount(4)
                .recordVideoSecond(15)
                .selectionMode(PictureConfig.MULTIPLE) // 多选 or 单选
                .previewImage(true) // 是否可预览图片
                .previewVideo(true) // 是否可预览视频
                .isCamera(true) // 是否显示拍照按钮
                .queryMaxFileSize(15f)
                .cutOutQuality(90) // 裁剪输出质量 默认100
                .minimumCompressSize(100) // 小于100kb的图片不压缩
                .videoQuality(1)// 视频录制质量 0 or 1
                .videoMaxSecond(15)////显示多少秒以内的视频or音频也可适用
                .forResult(object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(result: List<LocalMedia>) {
                        videoPath = result[0].realPath
                        showLoading()
                        if (!TextUtils.isEmpty(videoPath) && !videoFlag) {
                            val videoList  = mutableListOf<String>()
                            videoList.add(videoPath!!)
                            uploadVideo(videoList)
//                            compressVideo(videoPath!!)
                        }
                    }

                    override fun onCancel() {

                    }
                })
    }

    //从相册中选择图片和视频
    private fun chooseAlbum() {
        for (entity in mChooseList) {
            if (entity.fileType == "02") {
                videoNum = 1
            }
            if (entity.fileType == "01"){
                picNum += 1
            }
        }
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofAll()) // 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                .loadImageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                .setLanguage(LanguageConfig.ENGLISH)
                .maxSelectNum( 6 - picNum) // 最大图片选择数量
                .minSelectNum(0) // 最小选择数量
                .maxVideoSelectNum(1 - videoNum)
                .minVideoSelectNum(0)
                .isWithVideoImage(true)
                .imageSpanCount(4)
                .recordVideoSecond(15)
                .selectionMode(PictureConfig.MULTIPLE) // 多选 or 单选
                .previewImage(true) // 是否可预览图片
                .previewVideo(true) // 是否可预览视频
                .isCamera(false) // 是否显示拍照按钮
                .queryMaxFileSize(15f)
//                .selectionMedia(chooseList) // 是否传入已选图片
                .cutOutQuality(90) // 裁剪输出质量 默认100
                .minimumCompressSize(100) // 小于100kb的图片不压缩
                .videoQuality(1)// 视频录制质量 0 or 1
                .videoMaxSecond(15)////显示多少秒以内的视频or音频也可适用
                .forResult(object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(result: List<LocalMedia>) {
                        Log.e("result",Gson().toJson(result))
                        val picList:MutableList<String> = mutableListOf()
                        for (entity in result) {
                            if (entity.mimeType.startsWith("video")) {
                                videoPath = entity.realPath
                            } else if (entity.mimeType.startsWith("image")){
                                picList.add(entity.realPath)
                            }
                        }
                        showLoading()
                        if (!TextUtils.isEmpty(videoPath) && !videoFlag) {
//                            compressVideo(videoPath!!)
                            val videoList  = mutableListOf<String>()
                            videoList.add(videoPath!!)
                            uploadVideo(videoList)
                        }
                        if (picList.size > 0) {
                            uploadImage(picList)
                            picSize = picList.size
                        } else {
                            picSize = 0
                        }
                    }
                    override fun onCancel() {

                    }
                })
    }

    private var picFlag: Boolean = false
    /*
     上传视频图片List
     belongType 01 用户 02 活动
     fileType 01 图片 02 视频 03其他
    */
    private fun uploadImage(list: MutableList<String>) {
        if (list.size == 0) {
            dismissLoading()
            return
        }
        var path = ""
        if (list.size > 0) {
            val i = list[0].lastIndexOf("/")
            Log.d("选择图片路径:", i.toString() + "")
            path = list[0].substring(0, i)
            Log.d("选择图片路径:", path)
        }
        //luban  图片压缩
        Luban.with(this@PostEventActivity)
                .load(list[0]) //
                .ignoreBy(100) //忽略压缩大小
                .setTargetDir(path) //存放目录
                .filter { path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")) }
                .setCompressListener(object : OnCompressListener {
                    override fun onStart() {
                    }
                    override fun onSuccess(file: File) {
                        val belongType = "02"
                        val path = file.path
                        val fileType = "01"
                        val fileContent = Md5Util.imgToBase64(path)
                        val startTime = System.currentTimeMillis()
                        val fileName = startTime.toString() + ".png"
                        val infoEntity = UploadFileRequestBody(belongType, fileType, fileName, fileContent)
                        val body = Gson().toJson(infoEntity)
                        val requestBody = RequestBody.create(
                                MediaType.parse("application/json"), body)
                        viewModel.uploadFile(requestBody,object : RequestMultiplyCallback<FileEntity> {
                            override fun onSuccess(entity: FileEntity) {
                                mChooseList.add(entity)
                                list.remove(list[0])
                                uploadImage(list)
                                Log.e("eee","list" + Gson().toJson(list))
                                if (list.size == 0){
                                    picFlag = true
                                }
                                initCheckNum()
                                Log.e("eee","fileList==" + Gson().toJson(mChooseList))
                            }

                            override fun onError(e: ApiException) {
                                picFlag = true
                            }
                        })
                    }

                    override fun onError(e: Throwable) {
                        Log.d("图片压缩异常", e.message)
                    }
                }).launch()
    }

    var videoFlag:Boolean = false
    //视频上传
    private fun uploadVideo(list: MutableList<String>) {
        if (list.size == 0 ) {
            dismissLoading()
            return
        }
        var belongType:String = "02"
        var path:String = list[0]
        var fileType:String= "02"
        var fileContent:String = Md5Util.file2Base64(path)
        var startTime:Long = System.currentTimeMillis()
        var fileName:String = "$startTime.mp4"
        val infoEntity = UploadFileRequestBody(belongType, fileType, fileName, fileContent)
        val body = Gson().toJson(infoEntity)
        val requestBody = RequestBody.create(
                MediaType.parse("application/json"), body)
        viewModel.uploadFile(requestBody,object: RequestMultiplyCallback<FileEntity>{
            override fun onSuccess(entity: FileEntity) {
                mChooseList.add(0,entity)
                list.remove(list[0])
                Log.e("eee","list" + Gson().toJson(list))
                videoFlag = true
                initCheckNum()
                Log.e("eee","fileList==" + Gson().toJson(mChooseList))
            }

            override fun onError(e: ApiException?) {
                videoFlag = true
            }
        })
    }

    private fun initCheckNum() {
        if (mChooseList.size > 0) {
            for (i in mChooseList.size - 1 downTo 0) {
                if (mChooseList[i].fileType == "03") {
                    mChooseList.remove(mChooseList[i])
                }
            }
        }
        if (!TextUtils.isEmpty(videoPath)){//有视频
            if (picSize > 0){
                if (videoFlag && picFlag){//视频，图片上传完成
                    if (mChooseList.size < 6){
                        val entity = FileEntity("","03","")
                        mChooseList.add(entity)
                    }
                }
            } else {
                if (videoFlag ){//视频上传完成
                    if (mChooseList.size < 6){
                        val entity = FileEntity("","03","")
                        mChooseList.add(entity)
                    }
                }
            }

        } else {//无视频
            if (picSize > 0 && picFlag){
                if (mChooseList.size < 6){
                    val entity = FileEntity("","03","")
                    mChooseList.add(entity)
                }
            }
        }
        albumAdapter!!.notifyDataSetChanged()
        dismissLoading()
    }

    var videoPath: String? = null
    var picSize:Int = 0
    //压缩视频
    private fun compressVideo(videoPath: String) {
        Thread(Runnable {
            try {
                val retriever = MediaMetadataRetriever()
                retriever.setDataSource(this@PostEventActivity, Uri.parse(videoPath))
                val height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT) // 视频高度
                val width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH) // 视频宽度
                val bitrate = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE));
                val startTime = System.currentTimeMillis()
                mFileName = "$startTime.mp4"
                var videoOutCompressPath = getLocalFile().path
                VideoProcessor.processor(this@PostEventActivity)
                        .input(videoPath)
                        .output(videoOutCompressPath)
                        .outHeight(height.toInt())
                        .outWidth(width.toInt())
                        .bitrate(bitrate / 2)
                        .progressListener(VideoProgressListener() {
                            val intProgress = (it * 100).toInt()
                            val message = mHandler.obtainMessage() as Message
                            //message.what=0
                            //message.arg1 = intProgress
                            //mHandler.sendMessage(message)
                            if (intProgress == 100) {
                                message.what = 1
                                message.obj = videoOutCompressPath;
                                mHandler.sendMessage(message)
                            }
                        })
                        .process()
            } catch (e: Exception) {
                e.printStackTrace();
            }
        }).start()
    }

    private var mFileName: String? = null

    private fun getLocalFile(): File {
        return File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), mFileName)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    var mHandler = Handler(Handler.Callback { msg ->
        when (msg.what) {
            1 -> {
                var videoOutCompressPath = msg.obj as String
                Log.e("eee", videoOutCompressPath)
                val videoList  = mutableListOf<String>()
                videoList.add(videoOutCompressPath)
                uploadVideo(videoList)
            }
        }
        false
    })
}


